package com.example.xcService.pojo.channels.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.xcService.pojo.channels.ChannelResult;
import com.example.xcService.pojo.channels.ChannelService;
import com.example.xcService.pojo.tool.HttpTool;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;

/*
* 子轩
* */
@Slf4j
public class Plugin_ECARD_P035 implements ChannelService {

    @Override
    public ChannelResult QueryBalance(JSONObject apiConfig) {
        System.out.println("成功调用了QueryBalance");
        return  ChannelResult.success("success");
    }

    @Override
    public ChannelResult Submit(JSONObject apiConfig, Map<String, Object> data) {

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String timestamp = sdf.format(new Date());

            LinkedHashMap<String, Object> params = new LinkedHashMap<>();
            params.put("appId",apiConfig.getString("appId"));
            params.put("outOrderId",data.get("ChannelOrderCode"));
            params.put("uuid",data.get("AccountVal"));
            params.put("itemId",data.get("SUPProductId"));
            params.put("amount","1");
            params.put("timestamp",timestamp);

            String appSecret = apiConfig.getString("appSecret");
            params.put("appSecret",appSecret);

            String str = createLinkString(params);
            String sign = md5(str);
            params.put("sign",sign);
            String submitUrl = apiConfig.getString("SubmitUrl");
            params.remove("appSecret");
            String req = HttpTool.HttpPost2(submitUrl, params);
            JSONObject jsonObject = JSONObject.parseObject(req);
            String code = jsonObject.getString("code");
            String msg = jsonObject.getString("msg");

            if (code.equals("00")) {
                return ChannelResult.IN_PROCESS("充值中");
            }
            if (code.equals("-13")||code.equals("-10")||code.equals("-22")||code.equals("-23")||code.equals("-99")) {
                return ChannelResult.error(msg);
            }
            return ChannelResult.FAILED(msg);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("子轩提交订单接口错误：",e);
            return  ChannelResult.error("子轩提交订单接口错误");
        }

    }

    @Override
    public ChannelResult Query(JSONObject apiConfig, Map<String, Object> data) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String timestamp = sdf.format(new Date());
            HashMap<String, Object> params = new HashMap<>();
            params.put("appId",apiConfig.getString("appId"));
            params.put("outOrderId",data.get("ChannelOrderCode"));
            params.put("timestamp",timestamp);
            String appSecret = apiConfig.getString("appSecret");
            params.put("appSecret",appSecret);

            String str = createLinkString(params);
            String sign = md5(str);
            params.put("sign",sign);
            String queryUrl = apiConfig.getString("QueryUrl");
            params.remove("appSecret");
            String req = HttpTool.HttpPost2(queryUrl, params);

            JSONObject jsonObject = JSONObject.parseObject(req);
            String code = jsonObject.getString("code");
            String msg = jsonObject.getString("msg");
            String orderStatus = jsonObject.getString("orderStatus");
            String orderDesc = jsonObject.getString("orderDesc");

            if(code.equals("00")){
                if (orderStatus.equals("2")){
                    return ChannelResult.success("充值成功");
                }
                if (orderStatus.equals("1")) {
                    return ChannelResult.IN_PROCESS("充值中");
                }
                if(orderStatus.equals("4")){
                    return ChannelResult.error("联系管理员##"+orderDesc);
                }
                return ChannelResult.FAILED("充值失败");
            }
            return ChannelResult.error("查询失败##"+msg);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("子轩查询接口错误：",e);
            return  ChannelResult.error("子轩查询接口错误");
        }
    }


    @Override
    public ChannelResult Notify(JSONObject apiConfig, Map<String, Object> data) {
        System.out.println("成功调用了Notify");
        return  ChannelResult.success("success");
    }


    public static String createLinkString(HashMap<String,Object> params) {

        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);

        String prestr = "";

        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = (String) params.get(key);

            if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }

        return prestr;
    }

    /**
     * MD5指纹算法
     *
     * @param str
     * @return
     */
    public static String md5(String str) {
        if (str == null) {
            return null;
        }

        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(str.getBytes());
            return bytesToHexString(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 将二进制转换成16进制
     * @param src
     * @return
     */
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

}
